package pkg

import (
	"common/initialize"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strings"
)

type LongitudeAndLatitude struct {
	Status   string `json:"status"`
	Info     string `json:"info"`
	Infocode string `json:"infocode"`
	Count    string `json:"count"`
	Geocodes []struct {
		FormattedAddress string        `json:"formatted_address"`
		Country          string        `json:"country"`
		Province         string        `json:"province"`
		Citycode         string        `json:"citycode"`
		District         string        `json:"district"`
		Township         []interface{} `json:"township"`
		Neighborhood     struct {
			Name []interface{} `json:"name"`
			Type []interface{} `json:"type"`
		} `json:"neighborhood"`
		Building struct {
			Name []interface{} `json:"name"`
			Type []interface{} `json:"type"`
		} `json:"building"`
		Adcode   string `json:"adcode"`
		Street   string `json:"street"`
		Number   string `json:"number"`
		Location string `json:"location"`
		Level    string `json:"level"`
	} `json:"geocodes"`
}

func GetLongitudeAndLatitude(address string) (longitude string, latitude string, err error) {
	cf := initialize.Config.GaoDe
	url := "https://restapi.amap.com/v3/geocode/geo?key=" + cf.Key + "&address=" + address + "&output=JSON"
	// 创建一个GET请求
	resp, err := http.Get(url)
	if err != nil {
		return "", "", err
	}
	defer resp.Body.Close() // 确保关闭响应体
	// 检查响应状态
	if resp.StatusCode != http.StatusOK {
		return "", "", err
	}
	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", "", err
	}
	var s LongitudeAndLatitude
	err = json.Unmarshal(body, &s)
	if err != nil {
		return "", "", err
	}
	i2 := s.Geocodes[0]
	locationParts := strings.Split(i2.Location, ",")
	longitude = locationParts[0]
	latitude = locationParts[1]
	return longitude, latitude, nil
}
